<template>
  <div class="vehicle-info">
    <div class="vehicle-info__title">
      <div class="vehicle-info__title-text">
        {{ vehicleInfoData?.licenseNumber }}
      </div>
      <el-tag size="mini">
        {{ vehicleInfoData?.carStatus }}
      </el-tag>
    </div>

    <div class="vehicle-info__content">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="当前经纬度">
          {{ vehicleInfoData?.lon }},{{ vehicleInfoData?.lat }}
        </el-descriptions-item>

        <el-descriptions-item label="车辆位置">
          {{ vehicleInfoData?.address }}
        </el-descriptions-item>

        <el-descriptions-item label="车辆方向" :span="2">
          {{ vehicleInfoData?.direction }}
        </el-descriptions-item>

        <el-descriptions-item label="定位类型">
          {{ vehicleInfoData?.positioningType }}
        </el-descriptions-item>

        <el-descriptions-item label="最后定位时间">
          {{ vehicleInfoData?.lastLocationTime }}
        </el-descriptions-item>

        <el-descriptions-item label="最后更新时间">
          {{ vehicleInfoData?.lastLocationUpdateTime }}
        </el-descriptions-item>

        <el-descriptions-item label="历史轨迹">
          <el-button
            type="text"
            @click="handleViewHistory"
          >
            历史轨迹查看
          </el-button>
        </el-descriptions-item>
      </el-descriptions>
    </div>
  </div>
</template>

<script>
import { address } from '@/api/gps'
import vehicleGpsMixin from '@/views/vehicleService/js/vehicleGpsMixin'
export default {
  name: 'VehicleInfo',
  mixins: [vehicleGpsMixin],
  props: {
    vehicleInfo: {
      type: Object,
      default: () => ({})
    },
    authInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      vehicleInfoData: null
    }
  },

  watch: {
    vehicleInfo: {
      handler(val) {
        if (val?.lastGps) { // 使用可选链确保 val.lastGps 存在
          this.vehicleInfoFormat(val)
        } else {
          // 初始/空时设默认数据，避免空白UI
          this.vehicleInfoData = {
            licenseNumber: val?.license_plate_number || '未知车辆',
            address: '无GPS数据',
            lon: '-',
            lat: '-',
            direction: '-',
            positioningType: '-',
            carStatus: '-',
            lastLocationTime: '-',
            lastLocationUpdateTime: '-'
          }
        }
      }
      // deep: true
    }
  },

  methods: {
    async vehicleInfoFormat(info) {
      if (!info?.lastGps) {
        console.warn('车辆GPS数据为空')
        this.vehicleInfoData = {
          licenseNumber: info?.license_plate_number || '未知车辆',
          address: '无GPS数据',
          lon: '-', lat: '-', direction: '-',
          positioningType: '-', carStatus: '-',
          lastLocationTime: '-', lastLocationUpdateTime: '-'
        }
        return
      }

      const lon = info.lastGps.lastLon
      const lat = info.lastGps.lastLat
      console.log('lon, lat --------->', lon, lat)
      const degree = info.lastGps.lastCourse || 0
      const address = await this.getAddressByLonLat(lon, lat)
      const direction = this.getDirection(degree)
      const positioningType = this.getLocationInfoType(info.lastGps.lastLocationInfoType)
      const carStatus = this.getStatus(info.lastGps.status)
      this.vehicleInfoData = {
        licenseNumber: this.licenseNumberFormat(info.license_plate_number),
        lon,
        lat,
        address,
        direction,
        positioningType,
        carStatus,
        lastLocationTime: info.lastGps.lastLocationTime,
        lastLocationUpdateTime: info.lastGps.lastDataTime
      }
    },

    async getAddressByLonLat(lon, lat) {
      // 先验证坐标
      if (!lon || !lat || isNaN(lon) || isNaN(lat)) {
        console.warn('坐标无效，无法获取地址：', { lon, lat })
        return '位置未知' // 默认值
      }

      try {
        // 假设 address 函数返回的对象名为 res
        const res = await address({ 'lat': lat, 'lon': lon }, this.authInfo)

        const formattedAddress = res?.data?.formatted_address

        if (formattedAddress) {
          return formattedAddress
        } else {
          // 检查 API 是否返回了错误信息
          const errorMessage = res?.msg || res?.message || 'API响应无地址详情'
          console.warn('API响应无地址或结构异常。响应消息:', errorMessage, '完整响应:', res)
          return '地址暂不可用'
        }
      } catch (error) {
        console.error('获取地址失败：', error)

        return '加载地址出错'
      }
    },

    handleViewHistory() {
      this.$emit('viewHistory')
    }
  }
}
</script>

<style lang="scss" scoped>
.vehicle-info {
  height: 100%;
  &__title {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
    border-bottom: 1px solid #F5F5F5;
    height: 30px;

    &-text {
      color: #303133;
      font-weight: bold;
      margin-right: 10px;
    }
  }

  &__content {
    height: calc(100% - 30px);
    padding: 10px 0 0 0;
    overflow-y: auto;
  }
}
</style>
